<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天面Ai</title>
    <link rel="stylesheet" href="./css/chatInterface.css"> <!-- 导入外部 CSS 文件 -->
    <script src="./js/marked.min.js"></script> <!-- 引入 Marked.js -->
</head>

<body>

<div class="chat-container">
    <div class="chat-header">
        Ai 聊天室
    </div>
    <div class="header-button">
        <button onclick="connectWebSocket()">连接</button>
        <button onclick="closeWebSocket()">关闭链接</button>
        <button onclick="clearChat()">清除聊天记录</button>
    </div>
    <div class="chat-messages" id="chat-messages">
        <!-- 消息将在这里显示 -->
    </div>
    <div class="chat-input">
        <input type="text" id="message-input" placeholder="输入您的消息..."/>
        <button onclick="sendMessage()">发送</button>
    </div>
</div>
</body>

<script>

    //
    let receiveMessageTXT = true;
    let messageContainer;
    let messageContainerTXT = "";

    // 接收消息设置
    function receiveMessage(message) {


        if (receiveMessageTXT) {
            messageContainer = document.createElement('div');
            messageContainer.className = 'message received';
            // 使用 Marked.js 将消息内容转换为 HTML
            document.getElementById('chat-messages').appendChild(messageContainer);
            receiveMessageTXT = false;
        }

        if (message.indexOf("[|]") >= 0) {
            messageContainerTXT += message.replace("[|]", '');

            messageContainer.innerHTML = marked.parse(messageContainerTXT);

            receiveMessageTXT = true;
            messageContainerTXT = "";
            return;
        }

        messageContainerTXT += message;
        for (let index = 0; index < message.length; index++) {
            messageContainer.innerText += message.charAt(index);
            setTimeout(null, 100); // 调整速度，这里设置为100毫秒
        }

    }

    // 系统警告的函数
    function showAlert(message) {
        const alertBox = document.createElement('div');
        alertBox.className = 'alert';
        alertBox.textContent = message;
        document.body.appendChild(alertBox);

        // 3秒后自动隐藏警告
        setTimeout(() => {
            alertBox.classList.add('hide');
            setTimeout(() => {
                document.body.removeChild(alertBox);
            }, 500); // 500ms后从DOM中移除
        }, 3000); // 3000ms后开始隐藏
    }

    // 用户发送消息
    function setUser(message) {
        const messageContainer = document.createElement('div');
        messageContainer.textContent = message;
        messageContainer.className = 'message sent';
        document.getElementById('chat-messages').appendChild(messageContainer);

    }

    // 系统通知的函数
    function showNotification(message) {
        const notification = document.createElement('div');
        notification.className = 'notification';
        notification.textContent = message;
        document.body.appendChild(notification);

        // 3秒后自动隐藏通知
        setTimeout(() => {
            notification.classList.add('hide');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 500); // 500ms后从DOM中移除
        }, 3000); // 3000ms后开始隐藏
    }

    let websocket = null;

    // 从服务器获取消息
    function fetchMessages() {

        const client = Math.random().toString(36).substr(2);
        console.log(client)
        //连按webSocket节点
        if ('WebSocket' in window) {
            websocket = new WebSocket("/ws/" + client);
        } else {
            alert('您的浏览器不支持WebSocket')
            showAlert("您的浏览器不支持WebSocket")
            return;
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            showAlert("连接发生错误")
        }

        //连接成功建立的回调方法
        websocket.onopen = function () {
            showNotification("WebSocket连接成功")
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            receiveMessage(event.data)
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            showAlert("WebSocket连接已关闭")
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        }
    }


    // 发送消息
    function send(message) {
        websocket.send(message)
    }

    // 页面加载完成后，连接WebSocket
    window.onload = function () {
        fetchMessages()
    }
</script>

<script>
    //连接webSocket节点
    function connectWebSocket() {
        if (websocket) {
            websocket.close();
        }
        fetchMessages()
    }

    //关闭webSocket节点
    function closeWebSocket() {
        if (websocket) {
            websocket.close();
        }
    }

    // 清除聊天记录
    function clearChat() {
        const chatMessages = document.getElementById('chat-messages');
        chatMessages.innerHTML = ''; // 清除消息记录
    }

    // 发送消息
    function sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        if (message) {
            setUser(message)
            send(message)

            input.value = '';
            input.focus();
        }

    }
</script>

</html>
